package com.xiaotao.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.xiaotao.service.OrderService;
import com.xiaotao.util.PayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/alipay")
@Slf4j
public class AliPayController {

    @Resource
    private PayUtil payUtil;
    @Resource
    private OrderService orderService;

    /**
     * 支付请求
     * 前端传：orderId
     */
    @PostMapping("/pay")
    @ResponseBody
    public String pay(@RequestParam String orderId,
                      @RequestParam BigDecimal amount,
                      @RequestParam String subject) throws AlipayApiException {

        log.info("用户发起支付 orderId = {}", orderId);

        // 直接用订单号当 out_trade_no
        return payUtil.sendRequestToAlipay(orderId, amount, subject);
    }

    /**
     * 支付宝同步通知 (浏览器跳转)
     */
    @GetMapping("/return")
    public String returnUrl(String out_trade_no) {
        log.info("支付宝同步回调 return orderId = {}", out_trade_no);
        // 成功页面
        return "redirect:http://localhost:8081/paysuccess";
    }

    /**
     * 支付宝异步回调
     * 支持订单更新幂等
     */
    @PostMapping("/notify")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request) throws Exception {

        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }

        log.info("支付宝异步回调参数：{}", JSONObject.toJSONString(params));

        String outTradeNo = params.get("out_trade_no"); // 我们的订单号
        String tradeNo = params.get("trade_no");        // 支付宝交易号
        String tradeStatus = params.get("trade_status");
        String totalAmount = params.get("total_amount");

        // 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                payUtil.getAlipayPublicKey(),
                "UTF-8",
                "RSA2"
        );

        if (!signVerified) {
            log.error("支付宝验签失败");
            return "failure";
        }

        // 若支付成功
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            orderService.paySuccess(
                    outTradeNo,
                    tradeNo,
                    new BigDecimal(totalAmount),
                    (byte) 2  // 2 = 支付宝
            );
            log.info("订单 {} 支付成功", outTradeNo);
        }

        return "success";
    }

}
